package com.yumufeng.devutils;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity  {

    private EditText et_input;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_input = (EditText) findViewById(R.id.et_input);
        Button zhuanhuan = (Button) findViewById(R.id.bt_zhuanhuan);
        final TextView tv_dp = (TextView) findViewById(R.id.tv_dp);
        final TextView tv_sp = (TextView) findViewById(R.id.tv_sp);
        if (zhuanhuan != null) {
            zhuanhuan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String etInput =  et_input.getText().toString().trim();
                    if (TextUtils.isEmpty(etInput)) {
                        Toast.makeText(MainActivity.this, "输出的PX值不能为空!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    findViewById(R.id.ll_view).setVisibility(View.VISIBLE);
                    float v1 = Float.parseFloat(etInput);
                    int dp = px2dip(v1);
                    int sp = px2sp(v1);
                    tv_dp.setText(dp+"");
                    tv_sp.setText(sp+"");
                }
            });
        }
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param fontScale
     *            （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public int px2sp( float pxValue) {
        final float fontScale = this.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param pxValue
     * @param scale
     *            （DisplayMetrics类中属性density）
     * @return
     */
    public int px2dip(float pxValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}
